﻿using System;
using System.Collections.Generic;
using System.Linq;
using Atmk.WaterMeter.MIS.Commons.Interfaces;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Entities;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic
{
    /// <summary>
    /// 基本统计信息逻辑
    /// </summary>
    public class BaseInfoLogic : IBaseInfoLogic
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private readonly IDistrictLogic _districtLogic;
        private readonly IMergeQueryRepository _mergeQueryRepository;
        private readonly IRepository _repository;


        public BaseInfoLogic(
            IRepository repository,
            IMergeQueryRepository mergeQueryRepository,
            IDistrictLogic districtLogic
        )
        {
            _repository = repository;
            _mergeQueryRepository = mergeQueryRepository;
            _districtLogic = districtLogic;
        }

        /// <summary>
        ///     查询指定区域业主及水表数据//TODO：需要取消关联片区逻辑，保证该逻辑用于查询，不可调用其他查询逻辑
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="pageSize"></param>
        /// <param name="me"></param>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <param name="ow"></param>
        /// <returns></returns>
        public void SelectOwnerMeter(string uid, string id, int page, int pageSize, out List<Owner> ow,
            out List<Meter> me, string searchType = "", string searchValue = "")
        {
            try
            {
                var districtlist =
                    _repository.FindAllAsNoTracking<District>().ToList();
                //获取主区域及下所有子区域信息
                var districts = _districtLogic.GetDistrictsByUid(uid, districtlist);
                if (!string.IsNullOrEmpty(id)) districts = _districtLogic.DistrictEntitiesById(id, districtlist);

                if (districts.Count == 0)
                    districts = districtlist.Where(d => d.Id.ToString() == id).ToList();
                //获取业主信息
                var owners = _repository.FindAllAsNoTracking<Owner>().Where(o =>
                        districts.Select(d => d.Id.ToString()).Contains(o.DistrictId) &&
                        o.RecordState == (int)RecordStateEnum.Normal)
                    .ToList();
                //获取水表信息
                var meter = _repository.FindAllAsNoTracking<Meter>().Where(m =>
                        owners.Select(o => o.Id.ToString()).Contains(m.OwnerId) &&
                        m.RecordState == (int)RecordStateEnum.Normal)
                    .ToList();
                //条件筛选
                ow = QuerySearchOwner(searchType, searchValue, owners);
                me = QuerySearchMeter(searchType, searchValue, meter, ow);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                throw new Exception("查询指定区域业主及水表数据错误", e);
            }
        }

        /// <summary>
        ///     根据条件获取业主查询结果
        /// </summary>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <param name="owners"></param>
        /// <returns></returns>
        public List<Owner> QuerySearchOwner(string searchType, string searchValue,
            List<Owner> owners)
        {
            List<Owner> result;
            searchValue = searchValue.Trim();
            switch (searchType)
            {
                case "业主名称":
                    result = owners.Where(o => o.Name.Contains(searchValue)).ToList();
                    break;
                case "业主姓名":
                    result = owners.Where(o => o.Name.Contains(searchValue)).ToList();
                    break;
                case "门牌号":
                    result = owners.Where(o => o.HouseNumber.Contains(searchValue)).ToList();
                    break;
                case "手机号码":
                    result = owners.Where(o => o.Mobile.Contains(searchValue)).ToList();
                    break;
                default:
                    result = owners;
                    break;
            }

            return result;
        }

        /// <summary>
        ///     根据条件获取业主查询结果
        /// </summary>
        /// <param name="searchType"></param>
        /// <param name="searchValue"></param>
        /// <param name="meters"></param>
        /// <param name="owners"></param>
        /// <returns></returns>
        public List<Meter> QuerySearchMeter(string searchType, string searchValue,
            List<Meter> meters, List<Owner> owners = null)
        {
            List<Meter> result;
            switch (searchType)
            {
                case "表编号":
                    result = meters.Where(o => o.MeterNumber.Contains(searchValue.Trim())).ToList();
                    break;

                default:
                    result = meters;
                    break;
            }

            if (owners != null)
                result = result.Where(m => owners.Select(o => o.Id.ToString()).Contains(m.OwnerId)).ToList();
            return result;
        }

        /// <summary>
        ///     获取每页显示行数
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public int PageSize(string userId)
        {
            try
            {
                using (var context = Datas.ContextBuilder.Build())
                {
                    var user=context.User.FirstOrDefault(m => m.Id.ToString() == userId);
                    if (user==null)
                    {
                        throw new Exception("用户不存在");
                    }
                    else
                    {
                        return user.PageLines;
                    }
                }
                //    //获取用户信息
                //    var staffEntities = _repository.FindAllAsNoTracking<Staff>()
                //    .Where(s => s.Id.ToString() == userId).ToList();
                //if (staffEntities.Count == 0) throw new Exception("用户不存在");
                //return staffEntities.First().PageLines;
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
                return 100;
            }
        }

        #region 水表

       

        /// <summary>
        ///     获取业主与水表的数据集合
        /// </summary>
        /// <param name="sortOrder"></param>
        /// <param name="districtIds">片区编码集合</param>
        /// <returns></returns>
        public List<OwnerMeterViewModel> OwnerMeterData(string sortOrder,
            string[] districtIds)
        {
            //首先获取业主及水表信息
            var ownermeter = _mergeQueryRepository.SelectOwmerMeter(districtIds);
            //根据sortOrder 排序--默认按照业主编号
            switch (sortOrder)
            {
                default:
                    return ownermeter.OrderBy(o => o.OwnerId).ToList();
            }
        }

        #endregion
    }
}